package com.cql.framework.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.cql.common.constant.HttpStatus;
import com.cql.common.core.base.AjaxResult;
import com.cql.common.utils.MessageUtils;
import com.cql.common.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 * <p>
 * 用来解决匿名用户访问无权限资源时的异常
 *
 * @author cql
 */
@Component
public class PreAuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        logger.error("请求访问: " + request.getRequestURI() + " 接口， 没有访问权限");
        int code = HttpStatus.UNAUTHORIZED.getCode();
        String msg = MessageUtils.message("exception.unauthority");
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));

    }
}
